﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace WpfWordsLearner
{
	internal sealed class EncryptionManager
	{
		internal static byte[] Encrypt(byte[] data)
		{
			using (Aes algorithm = Aes.Create())
			using (ICryptoTransform encryptor = algorithm.CreateEncryptor((App.Current as App).key, (App.Current as App).iv))
				return Crypt(data, (App.Current as App).key, (App.Current as App).iv, encryptor);
		}

		internal static byte[] Decrypt(byte[] data)
		{
			using (Aes algorithm = Aes.Create())
			using (ICryptoTransform decryptor = algorithm.CreateDecryptor((App.Current as App).key, (App.Current as App).iv))
				return Crypt(data, (App.Current as App).key,(App.Current as App).iv, decryptor);
		}

		internal static string Encrypt(string data)
		{
			return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(data)));
		}

		[System.Diagnostics.DebuggerStepThrough()]
		internal static string Decrypt(string data)
		{
			return Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(data)));
		}

		static byte[] Crypt(byte[] data, byte[] key, byte[] iv, ICryptoTransform cryptor)
		{
			using (MemoryStream m = new MemoryStream())
			{
				using (Stream c = new CryptoStream(m, cryptor, CryptoStreamMode.Write))
					c.Write(data, 0, data.Length);
				return m.ToArray();
			}
		}
	}
}
